package com.hmkj.web.controller.upload;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.api.alibaba.AliyunOSSClient;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.web.controller.GenericController;
import com.xiaoleilu.hutool.lang.Base64;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 文件上传接口
 *
 * @author Vector
 * @create 2017-06-16 14:54
 */
@Api(description = "文件上传")
@RestController
@RequestMapping(value = GenericController.BASE_API_URL)
public class UploadJsonController extends GenericController {

    /**
     * 文件上传
     *
     * @param base64File
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @RequestMapping(value = "file/upload", method = RequestMethod.POST)
    public ResultEntity fileUpload(@ApiParam("base64压缩后字符串") @RequestParam String base64File) throws Exception {
        if (StrUtil.isBlank(base64File)) {
            throw new BussinessException("文件不能未空");
        }
        if (base64File.indexOf(",") > 0)
            base64File = base64File.substring(base64File.indexOf(",") + 1, base64File.length());
        byte[] b = Base64.decode(base64File);
        System.out.println(b.length);
        String uri;
        //上传到图片服务器
        try {
            //获取图片扩展名
            String fileName = RandomUtil.randomUUID() + ".jpg";
            uri = AliyunOSSClient.uploadFile(b, "/upload/web/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("图片上传失败");
        }

        return ok(uri);
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @RequestMapping(value = "file/upload2", method = RequestMethod.POST)
    public ResultEntity fileUpload(@RequestParam MultipartFile file) throws Exception {

        //判断图片是否为空
        if (file==null || file.isEmpty()) throw new BussinessException("文件不存在");

        String url;

        try {
            //获取图片扩展名
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String fileName = RandomUtil.randomUUID() + "." + extName;
            url = AliyunOSSClient.uploadFile(file.getBytes(), "/upload/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return fail("文件上传失败");
        }
        return ok(url);
    }
}
